<template>
  <div class="users">
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/index' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 添加按钮 -->
    <el-button class="addBtn" type="success" @click="addVisible=true">添加角色</el-button>
    <!-- 添加角色对话框 -->
    <el-dialog title="添加角色" :visible.sync="addVisible" width="40%">
      <el-form ref="form" :rules="rules" :model="form" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input placeholder="请输入角色名称" v-model="form.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input placeholder="请输入角色描述" v-model="form.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addVisible=false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 表格 -->
    <el-table :data="roleList">
      <el-table-column type="expand">
        <template slot-scope="obj">
          <p v-if="obj.row.children.length === 0">暂无权限</p>
          <el-row v-else class="border" v-for="child1 in obj.row.children" :key="child1.id">
            <el-col :span="4">
              <el-tag closable @close="delRight(obj.row,child1.id)">{{child1.authName}}</el-tag>
              <i class="el-icon-arrow-right"></i>
            </el-col>
            <el-col :span="20">
              <el-row v-for="child2 in child1.children" :key="child2.id">
                <el-col :span="4">
                  <el-tag closable type="success" class="mb-10" @close="delRight(obj.row,child2.id)">{{child2.authName}}</el-tag>
                  <i class="el-icon-arrow-right"></i>
                </el-col>
                <el-col :span="20">
                  <el-tag class="mr-5" @close="delRight(obj.row,child3.id)" closable type="warning" v-for="child3 in child2.children" :key="child3.id">{{child3.authName}}</el-tag>
                </el-col>
              </el-row>
            </el-col>
          </el-row>
        </template>
      </el-table-column>
      <el-table-column type="index" label="#" width="50%"></el-table-column>
      <el-table-column label="角色名称" prop="roleName"></el-table-column>
      <el-table-column label="描述" prop="roleDesc"></el-table-column>
      <el-table-column label="操作">
        <template v-slot:default="{ row }">
          <el-button plain size="small" @click="showEdit(row)" type="primary" icon="el-icon-edit"></el-button>
          <el-button plain size="small" type="danger" @click="delRole(row.id)" icon="el-icon-delete"></el-button>
          <el-button plain size="small" type="success" icon="el-icon-check" @click="showAllot(row)">分配权限</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分配权限对话框 -->
    <el-dialog title="分配权限" :visible.sync="allotVisible" @close='defaultSelected=[]' width="40%">
      <el-tree :data="rightList" show-checkbox node-key="id" :props="defaultProps" default-expand-all ref="tree" :default-checked-keys='defaultSelected'></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="allotVisible=false">取 消</el-button>
        <el-button type="primary" @click='allotRight'>分 配</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色对话框 -->
    <el-dialog title="修改角色" :visible.sync="editVisible" width="30%">
      <el-form ref="editForm" :rules="rules" :model="editForm" label-width="80px">
        <el-form-item label="角色ID">
          <el-tag type="info">{{ editForm.roleId }}</el-tag>
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input placeholder="请输入角色名称" v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input placeholder="请输入角色描述" v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editVisible=false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data () {
    return {
      roleList: [],
      rightList: [],
      defaultProps: {
        children: 'children',
        label: 'authName',
        roleId: ''
      },
      defaultSelected: [],
      flag: false,
      showId: '',
      showName: '',
      showDesc: '',
      editVisible: false,
      addVisible: false,
      allotVisible: false,
      form: {
        roleName: '',
        roleDesc: ''
      },
      editForm: {
        roleId: '',
        roleName: '',
        roleDesc: ''
      },
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        roleDesc: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 渲染列表
    async getRoleList () {
      const { data, meta } = await this.$axios.get('roles')
      if (meta.status === 200) {
        console.log(data)
        this.roleList = data
      } else {
        this.$message.error(meta.msg)
      }
    },
    // 添加角色
    async addRole () {
      try {
        this.roleList.forEach(item => {
          if (item.roleName === this.form.roleName) {
            this.flag = true
          }
        })
        if (this.flag) {
          this.flag = false
          return this.$message.error('角色名称已存在')
        }
        await this.$refs.form.validate()
        const { meta } = await this.$axios.post('roles', this.form)
        if (meta.status === 201) {
          this.addVisible = false
          this.getRoleList()
          this.$refs.form.resetFields()
        }
      } catch (e) {
        console.log(e)
      }
    },
    // 删除权限
    async delRight (row, rightId) {
      try {
        const { meta, data } = await this.$axios.delete(
          `roles/${row.id}/rights/${rightId}`
        )
        if (meta.status === 200) {
          this.$message.success(meta.msg)
          row.children = data
        }
      } catch (e) {
        console.log(e)
      }
    },
    // 显示分配框
    showAllot (row) {
      this.allotVisible = true
      this.defaultProps.roleId = row.id
      this.$axios.get('rights/tree').then(res => {
        this.rightList = res.data
        // row.children.forEach(item => item.children.forEach(item => item.children.forEach(item => this.defaultSelected.push(item.id))))
        this.forRow(row)
      })
    },
    // 封装遍历children
    forRow (item) {
      if (item.children) {
        item.children.forEach(item => {
          return this.forRow(item)
        })
      } else {
        this.defaultSelected.push(item.id)
      }
    },
    // 确认分配权限
    async allotRight () {
      try {
        const roleId = this.defaultProps.roleId
        const half = this.$refs.tree.getHalfCheckedKeys()
        const all = this.$refs.tree.getCheckedKeys()
        const rids = half.concat(all).join(',')
        const { meta } = await this.$axios.post(`roles/${roleId}/rights`, { rids })
        if (meta.status === 200) {
          this.$message.success(meta.msg)
          this.allotVisible = false
          this.getRoleList()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (e) {
        console.log(e)
      }
    },
    // 显示编辑框
    showEdit (row) {
      this.editVisible = true
      this.editForm.roleName = row.roleName
      this.editForm.roleDesc = row.roleDesc
      this.editForm.roleId = row.id
    },
    // 确认修改
    async editRole () {
      try {
        await this.$refs.editForm.validate()
        const { roleId, roleName, roleDesc } = this.editForm
        const { meta } = await this.$axios.put(`roles/${roleId}`, {
          roleName,
          roleDesc
        })
        if (meta.status === 200) {
          this.editVisible = false
          this.$message.success('修改成功')
          this.getRoleList()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (e) {
        console.log(e)
      }
    },
    // 删除用户功能
    async delRole (id) {
      try {
        await this.$confirm('亲,你确定要删除此角色吗', '温馨提示', {
          type: 'warning'
        })
        const { meta } = await this.$axios.delete(`roles/${id}`)
        if (meta.status === 200) {
          this.$message.success(meta.msg)
          this.getRoleList()
        } else {
          this.$message.error(meta.msg)
        }
      } catch (e) {
        console.log(e)
      }
    }
  },
  created () {
    this.getRoleList()
  }
}
</script>

<style lang='scss' scoped>
.el-table {
  margin-top: 20px;
}
.el-breadcrumb {
  height: 40px;
  line-height: 40px;
  border-bottom: 1px solid #ccc;
  margin-bottom: 10px;
}
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
.border {
  padding: 10px 0;
  border-bottom: 1px dotted #ccc;
}
.mr-5 {
  margin-right: 5px;
}
.mb-10 {
  margin-bottom: 10px;
}
</style>
